package com.surekam.dma.web.content;

import java.util.List;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.surekam.dma.entity.content.Directory;
import com.surekam.dma.service.ServiceException;
import com.surekam.dma.service.content.DirectoryManager;
import com.surekam.dma.web.CrudActionSupport;

@Namespace("/content")
@Results( { @Result(name = CrudActionSupport.RELOAD, location = "directory.action", type = "redirect") })
public class DirectoryAction extends CrudActionSupport<Directory> {

	private static final long serialVersionUID = 2328355023777017062L;
	private Long id;
	private Directory entity;
	private String name;
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}

	private DirectoryManager directoryManager;
	private Page<Directory> page = new Page<Directory>(2);// 每页8条记录

	@Autowired
	public void setDirectoryManager(DirectoryManager directoryManager) {
		this.directoryManager = directoryManager;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Directory getModel() {
		return entity;
	}

	public String input() throws Exception {
		return INPUT;
	}

	public String save() throws Exception {
		directoryManager.saveDirectory(entity);
		addActionMessage("保存用户成功");
		return RELOAD;
	}

	public String delete() throws Exception {
		try {
			directoryManager.deleteDirectory(id);
			addActionMessage("删除用户成功");
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionMessage("删除用户失败");
		}
		return RELOAD;
	}

	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = directoryManager.getDirectory(id);
		} else {
			entity = new Directory();
		}
	}

	public Page<Directory> getPage() {
		return page;
	}
	
	public String list() throws Exception {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		// 设置默认排序方式
		if (!page.isOrderBySetted()) {
			page.setOrderBy("name");
			page.setOrder(Page.ASC);
		}
		page = directoryManager.searchDirectory(page, filters);
		return SUCCESS;
	}
}
